"""
注册页面对象类
"""
import logging
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from tests.page_objects.base_page import BasePage


class RegisterPage(BasePage):
    """注册页面的页面对象模型"""
    
    # 页面元素定位器
    USERNAME_INPUT = (By.CSS_SELECTOR, "input[placeholder='请输入用户名']")
    PASSWORD_INPUT = (By.CSS_SELECTOR, "input[placeholder='请输入密码']")
    CONFIRM_PASSWORD_INPUT = (By.CSS_SELECTOR, "input[placeholder='请确认密码']")
    EMAIL_INPUT = (By.CSS_SELECTOR, "input[placeholder='请输入邮箱']")
    PHONE_INPUT = (By.CSS_SELECTOR, "input[placeholder='请输入手机号']")
    NAME_INPUT = (By.CSS_SELECTOR, "input[placeholder='请输入姓名']")
    SEX_MALE_RADIO = (By.XPATH, "//span[text()='男']/preceding-sibling::span")
    SEX_FEMALE_RADIO = (By.XPATH, "//span[text()='女']/preceding-sibling::span")
    REGISTER_BUTTON = (By.XPATH, "//button[contains(.,'注册')]")
    ERROR_MESSAGE = (By.CLASS_NAME, "el-form-item__error")
    SUCCESS_MESSAGE = (By.CLASS_NAME, "el-message--success")
    LOGIN_LINK = (By.CSS_SELECTOR, ".login-link")
    
    def __init__(self, driver):
        """
        初始化注册页面对象
        
        Args:
            driver: WebDriver实例
        """
        super().__init__(driver)
        
    def open_register_page(self):
        """
        打开注册页面
        """
        logging.info("打开注册页面")
        self.open("register")  # 对应 http://localhost:8080/register
        self.wait_for_page_load()
        return self
        
    def enter_username(self, username):
        """
        输入用户名
        
        Args:
            username: 要输入的用户名
        """
        logging.info(f"输入用户名: {username}")
        self.input_text(self.USERNAME_INPUT, username)
        return self
        
    def enter_password(self, password):
        """
        输入密码
        
        Args:
            password: 要输入的密码
        """
        logging.info(f"输入密码: {'*' * len(password)}")
        self.input_text(self.PASSWORD_INPUT, password)
        return self
        
    def enter_confirm_password(self, confirm_password):
        """
        输入确认密码
        
        Args:
            confirm_password: 要输入的确认密码
        """
        logging.info(f"输入确认密码: {'*' * len(confirm_password)}")
        self.input_text(self.CONFIRM_PASSWORD_INPUT, confirm_password)
        return self
        
    def enter_email(self, email):
        """
        输入邮箱
        
        Args:
            email: 要输入的邮箱
        """
        logging.info(f"输入邮箱: {email}")
        self.input_text(self.EMAIL_INPUT, email)
        return self
        
    def enter_phone(self, phone):
        """
        输入手机号
        
        Args:
            phone: 要输入的手机号
        """
        logging.info(f"输入手机号: {phone}")
        self.input_text(self.PHONE_INPUT, phone)
        return self
        
    def enter_name(self, name):
        """
        输入姓名
        
        Args:
            name: 要输入的姓名
        """
        logging.info(f"输入姓名: {name}")
        self.input_text(self.NAME_INPUT, name)
        return self
        
    def select_sex(self, sex):
        """
        选择性别
        
        Args:
            sex: 性别，'男'或'女'
        """
        logging.info(f"选择性别: {sex}")
        if sex == "男":
            self.click(self.SEX_MALE_RADIO)
        elif sex == "女":
            self.click(self.SEX_FEMALE_RADIO)
        else:
            logging.warning(f"未知的性别值: {sex}，默认选择'男'")
            self.click(self.SEX_MALE_RADIO)
        return self
        
    def click_register_button(self):
        """
        点击注册按钮
        """
        logging.info("点击注册按钮")
        self.click(self.REGISTER_BUTTON)
        return self
        
    def register(self, user_data):
        """
        执行完整的注册流程
        
        Args:
            user_data: 包含用户注册数据的字典
        """
        logging.info(f"使用数据注册新用户: {user_data.get('username')}")
        # 填写表单字段
        self.enter_username(user_data.get('username', ''))
        self.enter_password(user_data.get('password', ''))
        self.enter_confirm_password(user_data.get('confirmPassword', ''))
        self.enter_email(user_data.get('email', ''))
        self.enter_phone(user_data.get('phone', ''))
        self.enter_name(user_data.get('name', ''))
        
        # 性别默认设为男
        sex = user_data.get('sex', '男')
        if sex:
            self.select_sex(sex)
        
        # 点击注册按钮
        self.click_register_button()
        return self
                
    def get_error_message(self):
        """
        获取错误消息
        
        Returns:
            错误消息文本列表
        """
        try:
            error_elements = self.find_elements(self.ERROR_MESSAGE)
            error_messages = [element.text for element in error_elements if element.text.strip()]
            logging.info(f"获取到错误信息: {error_messages}")
            return error_messages
        except Exception as e:
            logging.error(f"获取错误信息失败: {e}")
            return []
            
    def get_success_message(self):
        """
        获取成功消息
        
        Returns:
            成功消息文本
        """
        try:
            self.wait.until(EC.visibility_of_element_located(self.SUCCESS_MESSAGE))
            message = self.get_text(self.SUCCESS_MESSAGE)
            logging.info(f"获取到成功信息: {message}")
            return message
        except Exception as e:
            logging.error(f"获取成功信息失败: {e}")
            return ""
            
    def click_login_link(self):
        """
        点击登录链接
        """
        logging.info("点击登录链接")
        self.click(self.LOGIN_LINK)
        return self
        
    def is_at_register_page(self):
        """
        检查是否在注册页面
        
        Returns:
            布尔值，表示是否在注册页面
        """
        current_url = self.driver.current_url
        return "register" in current_url
        
    def is_registration_successful(self):
        """
        检查注册是否成功
        
        Returns:
            布尔值，表示注册是否成功
        """
        success_msg = self.get_success_message()
        return "成功" in success_msg 